package com.loe.mvp.util.selecter;

import android.view.View;

import java.util.ArrayList;

/**
 * 选择器
 * Created by zls on 2016/1/16.
 */
public class Selector implements View.OnClickListener
{
    private int index = -1;

    private SelectItem nowItem;

    private ArrayList<SelectItem> list;
    private ArrayList<OnSelectListener> onSelectListeners;

    public Selector()
    {
        list = new ArrayList<>();
        onSelectListeners = new ArrayList<>();
    }

    /**
     * 添加元素
     */
    public Selector add(SelectItem selectItem)
    {
        list.add(selectItem);
        selectItem.view.setOnClickListener(this);
        return this;
    }

    /**
     * 选择
     */
    public void select(View view)
    {
        for (int i = 0; i < list.size(); i++)
        {
            SelectItem item = list.get(i);
            if (view.equals(item.view))
            {
                item.selectIn();
                index = i;
                nowItem = item;
            } else
            {
                item.selectOut();
            }
        }
        if (onSelectListeners.size() != 0 && nowItem != null)
        {
            for (OnSelectListener onSelectListener : onSelectListeners)
            {
                onSelectListener.select(nowItem, index);
            }
        }
    }

    /**
     * 选择
     */
    public void select(int n)
    {
        for (int i = 0; i < list.size(); i++)
        {
            SelectItem item = list.get(i);
            if (n == i)
            {
                item.selectIn();
                index = i;
                nowItem = item;
            } else
            {
                item.selectOut();
            }
        }
        if (onSelectListeners.size() != 0 && nowItem != null)
        {
            for (OnSelectListener onSelectListener : onSelectListeners)
            {
                onSelectListener.select(nowItem, index);
            }
        }
    }

    public SelectItem getNowItem()
    {
        return nowItem;
    }

    public int getIndex()
    {
        return index;
    }

    @Override
    public void onClick(View v)
    {
        select(v);
    }

    /**
     * 添加选择监听器
     */
    public void addOnSelectListener(OnSelectListener onSelectListener)
    {
        onSelectListeners.add(onSelectListener);
    }

    /**
     * 选择监听器
     */
    public interface OnSelectListener
    {
        void select(SelectItem selectItem, int i);
    }
}
